<script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';

  import { isDark } from '@/hooks/core/useToggleDark';
  import { useLocale } from '@/locales/useLocale';
  import { useUserinfoStore } from '@/store/module/useUserStore';
  import { reqUpdateAvatar } from '@/api/module/userApi';

  const imageUrl = ref('');

  //@ts-ignore
  const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  };

  const imageType = ['image/svg+xml', 'image/jpeg', 'image/png'];

  //@ts-ignore
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!imageType.includes(rawFile.type)) {
      ElMessage.error('Avatar picture must be JPG format!');
      return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('Avatar picture size can not exceed 2MB!');
      return false;
    }
    const userStore = useUserinfoStore();
    const formData = new FormData();
    formData.set('file', rawFile);
    formData.set('id', String(userStore.id));
    reqUpdateAvatar(formData).then((res) => {
      ElMessage.success({ message: res.msg });
      userStore.getUserinfo();
    });
    return true;
  };

  const { t } = useLocale();
</script>

<template>
  <div class="flex-justify-items-center py-6 enter-y">
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
  <div class="mb-2 enter-y">
    <el-alert
      :title="t('message.sys.profile.avatarTitle')"
      type="warning"
      :description="t('message.sys.profile.avatarDesc')"
      :effect="isDark ? 'dark' : 'light'"
      show-icon
      :closable="false"
      center
    />
  </div>
</template>

<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
